import 'dart:convert';

import 'package:dart_sm/dart_sm.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:ls_work/keyboard/with_secure_keyboard.dart';
import 'package:ls_work/login/page/login_page.dart';
import 'package:ls_work/login/page/user_manager.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:base_flutter/base_flutter.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/res/resources.dart';
import 'package:ls_work/util/sm4_utils.dart';
import 'package:ls_work/util/toast.dart';
import 'package:ls_work/util/utils.dart';
import 'package:ls_work/widgets/app_bar.dart';
import 'package:ls_work/widgets/my_button.dart';
import 'package:ls_work/widgets/text_field.dart';
import 'package:keyboard_actions/keyboard_actions.dart';
import 'package:flutterlifecyclehooks/flutterlifecyclehooks.dart';
import 'package:oktoast/oktoast.dart';

import '../../keyboard/secure_keyboard_type.dart';
import '../../util/native_toast.dart';


/// design/1注册登录/index.html#artboard9
class ResetPasswordPage extends StatefulWidget {
  @override
  _ResetPasswordPageState createState() => _ResetPasswordPageState();
}

class _ResetPasswordPageState extends State<ResetPasswordPage> with LifecycleMixin {
  //定义一个controller
  TextEditingController _oldPasswordController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _confiemController = TextEditingController();
  TextEditingController _verifyCodeController = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  final FocusNode _nodeText3 = FocusNode();
  final FocusNode _nodeText4 = FocusNode();
  KeyboardActionsConfig?_config;
  bool _isClick = false;

  String? verifyCode;

  @override
  void initState() {
    //监听输入改变
    // _oldPasswordController.addListener(_verify);
    // _confiemController.addListener(_verify);
    // _passwordController.addListener(_verify);
    NativeUtils.setSecureScreen(true);
    _config =
        Utils.getKeyboardActionsConfig([_nodeText1, _nodeText2, _nodeText3]);
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((duration){
      getVerifyCode();
    });

  }

  void _verify() {
    String name = _oldPasswordController.text;
    String vCode = _passwordController.text;
    String password = _confiemController.text;
    bool isClick = true;
    if (name.isEmpty) {
      isClick = false;
    }
    if (vCode.isEmpty) {
      isClick = false;
    }
    if (password.isEmpty) {
      isClick = false;
    }
    if (isClick != _isClick) {
      setState(() {
        _isClick = isClick;
      });
    }
  }

  void _reset() {
    // Toast.show("确认......");
    changePassword();
  }

  Future<void> changePassword() async {
    var oldPassword = _oldPasswordController.text.sm4;
    var newPassword = _passwordController.text.sm4;
    // print(oldPassword);
    // return;
    if(_oldPasswordController.text.isEmpty){
      Toast.show('请输入原始密码',);
      return;
    }
    if(_passwordController.text.isEmpty){
      Toast.show('请输入新密码',);
      return;
    }

    if(_confiemController.text.isEmpty){
      Toast.show('请再次输入新密码',);
      return;
    }

    if(_passwordController.text!=_confiemController.text){
      Toast.show('两次密码输入不一致',);
      return;
    }
    if(_verifyCodeController.text.isEmpty){
      Toast.show('请输入验证码',);
      return;
    }


    SVProgressHUD progressHUD = SVProgressHUD(context);
    progressHUD.showProgress(hint: '提交中...');


    var map = {
      "newPwd":newPassword,
      "oldPwd":oldPassword,
      "cryptoType":'sm4',
      "code":_verifyCodeController.text,
    };
    // print(newPassword);
    // return;
    try{
      var data = await HttpGo.instance.postData(HttpApi.changePassword,data: map,options: Options(contentType: Headers.formUrlEncodedContentType));
      progressHUD.closeProgress();
      if("0"==data['code']){
        UserManager.instance.logout();
        Go().pushRemoveUntil(LoginPage(error: '当前账号密码发生变化，请重新登录',));
        // NavigatorUtils.push(context, LoginRouter.loginPage, clearStack: true);
      }else{

        Toast.show(data['msg']);
        getVerifyCode();
      }
    }catch(e){
      progressHUD.closeProgress();
      Toast.show(e.toNetError());
      getVerifyCode();
    }
  }

  final _secureKeyboardController = SecureKeyboardController();


  @override
  Widget build(BuildContext context) {
    return WithSecureKeyboard(controller: _secureKeyboardController, child: Scaffold(
      appBar:  MyAppBar(
        title: "修改密码",
      ),
      body: defaultTargetPlatform == TargetPlatform.iOS
          ? KeyboardActions(
        config: _config!,
        child: _buildBody(),
      )
          : SingleChildScrollView(
        child: _buildBody(),
      ),
    ));
  }

  _buildBody() {
    return Padding(
      padding: const EdgeInsets.only(left: 16.0, right: 16.0, top: 20.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          const Text(
            "重置登录密码",
            style: TextStyles.textBoldDark26,
          ),
          Gaps.vGap16,
          MyTextField(
            focusNode: _nodeText1,
            config: _config!,
            controller: _oldPasswordController,
            maxLength: 50,
            isInputPwd: true,
            hintText: "填写原始密码",
            enableInteractiveSelection: false,
            onTap: (){
              _secureKeyboardController.show(
                type: SecureKeyboardType.ALPHA_NUMERIC,
                focusNode: _nodeText1,
                initText: _oldPasswordController.text,
                hintText: '填写原始密码',
                // Use onCharCodesChanged to have text entered in real time.
                onCharCodesChanged: (List<int> charCodes) {
                  _oldPasswordController.text = String.fromCharCodes(charCodes);
                },
              );
            },
          ),
          Gaps.vGap8,
          MyTextField(
            focusNode: _nodeText2,
            isInputPwd: true,
            controller: _passwordController,
            maxLength: 50,
            hintText: "填写新密码",
            enableInteractiveSelection: false,
            onTap: (){
              _secureKeyboardController.show(
                type: SecureKeyboardType.ALPHA_NUMERIC,
                focusNode: _nodeText2,
                initText: _passwordController.text,
                hintText: '填写新密码',
                // Use onCharCodesChanged to have text entered in real time.
                onCharCodesChanged: (List<int> charCodes) {
                  _passwordController.text = String.fromCharCodes(charCodes);
                },
              );
            },
          ),
          Gaps.vGap8,
          MyTextField(
            focusNode: _nodeText3,
            isInputPwd: true,
            controller: _confiemController,
            maxLength: 50,
            enableInteractiveSelection: false,
            hintText: "再次填写确认",
            onTap: (){
              _secureKeyboardController.show(
                type: SecureKeyboardType.ALPHA_NUMERIC,
                focusNode: _nodeText3,
                initText: _confiemController.text,
                hintText: '再次填写确认',
                // Use onCharCodesChanged to have text entered in real time.
                onCharCodesChanged: (List<int> charCodes) {
                  _confiemController.text = String.fromCharCodes(charCodes);
                },
              );
            },
          ),

          Gaps.vGap8,
          Row(
            children: [
              MyTextField(
                focusNode: _nodeText4,
                isInputPwd: false,
                controller: _verifyCodeController,
                maxLength: 50,
                // enableInteractiveSelection: false,
                hintText: "输入图形验证码",
                // onTap: (){
                //   _secureKeyboardController.show(
                //     type: SecureKeyboardType.ALPHA_NUMERIC,
                //     focusNode: _nodeText3,
                //     initText: _confiemController.text,
                //     hintText: '输入图形验证码',
                //     // Use onCharCodesChanged to have text entered in real time.
                //     onCharCodesChanged: (List<int> charCodes) {
                //       _confiemController.text = String.fromCharCodes(charCodes);
                //     },
                //   );
                // },
              ).setWeight(1),

              if (!verifyCode.isNullOrEmpty())
                Image.memory(base64Decode(verifyCode!)).onTap(() {
                  getVerifyCode();
                })
              else
                CommonText('获取验证码', textColor: Colours.app_main)
                    .addToContainer(
                    padding:
                    EdgeInsets.symmetric(horizontal: 8, vertical: 4))
                    .onTap(() {
                  getVerifyCode();
                })
            ],
          ),
          Gaps.vGap10,
          Gaps.vGap15,
          MyButton(
            onPressed: _reset,
            text: "确认",
          )
        ],
      ),
    );
  }

  @override
  void onAppHide() {
    if(mounted){
      _oldPasswordController.clear();
      _passwordController.clear();
      _confiemController.clear();
    }
    super.onAppHide();
  }

  @override
  void dispose() {
    if(mounted){
      NativeUtils.setSecureScreen(false);
      _oldPasswordController.dispose();
      _passwordController.dispose();
      _confiemController.dispose();
      _nodeText1.dispose();

    }
    super.dispose();
  }


  ///获取验证码
  Future<void> getVerifyCode() async {
    try {
      var data = await HttpGo.instance.dio!.post(
          "${HttpApi.baseUrl}checkCode/getCheckCode",
          options: Options(
              contentType: Headers.jsonContentType,
              responseType: ResponseType.plain));


      var prik = data!.toString().substring(35, 35 + 64);
      var pck = data.toString().substring(35 + 64, 35 + 64 + 130);

      var imageData = data.toString().substring(0, 35) +
          data.toString().substring(35 + 64 + 130);
      var image = SM2.decrypt(imageData, prik!);

      setState(() {
        verifyCode = jsonDecode(image)['data'];
      });

      // UserManager.instance.saveItemKey(prik!);
    } catch (e) {
      print("error===>${e}");
    }
  }
}
